﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Twipler.WebApp
{
    [System.AttributeUsage(System.AttributeTargets.Class)]
    public class QueryStringHash : System.Attribute
    {
        public QueryStringHash()
        {}

        public static string Protect(string url)
        {
            if (url.IndexOf("?") == -1)
                return url;

            string queryString = url.Substring(url.IndexOf("?") + 1).Replace("&", "").Replace("=", "");

            return url + "&hash=" + MakeHash(queryString, App.Current.PrivateUniqueSecret, DateTime.Now);
        }

        public bool Validate(NameValueCollection nameValueCollection)
        {
            if (nameValueCollection.Count == 0)
                return true;

            // Remove the hash value
            string hash = nameValueCollection["hash"];
            
            // Concatinate name values
            string qsString = ConcatinateValues(nameValueCollection);
            DateTime now = DateTime.Now;

            // Was hash created in this hour
            if (hash == MakeHash(qsString, App.Current.PrivateUniqueSecret, now))
                return true;

            // Or was hash created in the previous hour (consider edge case)
            if (hash == MakeHash(qsString, App.Current.PrivateUniqueSecret, now.AddHours(-1)))
                return true;

            // Otherwise not happy.
            return false;
        }

        private static string MakeHash(string qsString, string salt, DateTime period)
        {
            return Encode(string.Format("{0}{1}{2:yyMMddhh}", qsString, "x", period));
        }

        private static string ConcatinateValues(NameValueCollection nvc)
        {
            StringBuilder blob = new StringBuilder();
            
            for (int i = 0; i < nvc.Count; i++)
                if (nvc.GetKey(i) != "hash")
                    blob.AppendFormat("{0}{1}", nvc.GetKey(i), nvc[i]);
            
            return blob.ToString();
        }

        private static string Encode(string input)
        {
            return Convert.ToBase64String((new SHA1CryptoServiceProvider()).ComputeHash(Encoding.ASCII.GetBytes(input))).Replace("+",".");
        }
    }
    
}
